//
//  ProjectsViewModel.swift
//  Git@OSC
//
//  Created by AeternChan on 5/27/15.
//  Copyright (c) 2015 oschina. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import ReactiveCocoa

enum ProjectGroup : String {
    case Recommended    =   "featured"
    case Popular        =   "popular"
    case RecentUpdated  =   "latest"
}

class ProjectsViewModel: NSObject {
    
    var projects = [Project]()
    var group: ProjectGroup?
    var userID: Int?
    var page = MutableProperty<Int>(0)
    var allProjectsLoaded = false
    
    convenience init(group: ProjectGroup) {
        self.init()
        self.group = group
    }
    
    convenience init(userID: Int) {
        self.init()
        self.userID = userID
    }
    
    func fetchProjects(refresh: Bool = false) {
        
        Alamofire.request(.GET, API.projects + group!.rawValue, parameters: ["page": page.value])
                 .responseJSON { response in
                    
                    if response.result.isSuccess {
                        if refresh {
                            self.projects.removeAll(keepCapacity: false)
                            self.page.value = 0
                        }
                        
                        let json = JSON(response.result.value!)
                        
                        for (_, projectJSON) in json {
                            let project = Project(projectJSON)
                            self.projects.append(project)
                        }
                        
                        self.page.value++
                    } else {
                        
                    }
                }
    }
    
    func refresh() {
        fetchProjects(true)
    }
}
